package com.example.task;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CatAsyncAopService {

    @Autowired
    private AsyncProxy asyncProxy;


    @Pointcut("@annotation(com.example.task.CatAsync)")
    public void catAsync() {}


    @Around("catAsync()")
    public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String transactionName = method.getDeclaringClass().getName() + "." + method.getName();
        System.out.println("--------------------CatAsyncAopService begin ----------------");
        async(() -> {
            try {
                pjp.proceed();
            } catch (Throwable e) {
            }
        }, transactionName);
        System.out.println("--------------------CatAsyncAopService end ----------------");
    }



    private void async(Func func, String methodName) {
        try {
            asyncProxy.doAsync(func, methodName);
        } catch (Throwable e) {
            throw e;
        } finally {
        }
    }

    @Component
    static class AsyncProxy {

        private static final String CAT_TRANSACTION_TYPE_ASYNC_PROXY_METHOD = "AsyncProxy.Method";
        /**
         *
         * @param func
         * @param methodName 需要在切面中获取到此参数
         */
        @Async
        public void doAsync(Func func, String methodName) {
            func.apply();
        }

    }


}
